﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.Objects;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;

namespace SimpleData.Tests.Helpers
{
	public class DbApi
	{
		public DbApi( Runtime runtime, ObjectContext context )
		{
			this.Runtime = runtime;
			this.Context = context;
		}

		public Runtime Runtime
		{
			get;
			private set;
		}

		public ObjectContext Context
		{
			get;
			private set;
		}

		private DbConnection CreateConnection()
		{
			return new SqlConnection( ConfigurationManager.ConnectionStrings[ "DbAPI" ].ConnectionString );
		}

		public void Execute( string sql )
		{
			using ( var connection = this.CreateConnection() )
			{
				using ( var command = connection.CreateCommand() )
				{
					command.CommandText = sql;
					command.CommandType = System.Data.CommandType.Text;

					connection.Open();

					try
					{
						command.ExecuteNonQuery();
					}
					finally
					{
						connection.Close();
					}
				}
			}
		}

		public void Execute( TextReader reader )
		{
			this.Execute( reader.ReadToEnd() );
		}

		public void ExecuteFile( string fileName )
		{
			this.Execute( this.Runtime.OpenEmbeddedResource( fileName ) );
		}
	}
}
